package util.components;




import javax.swing.JTextField;
import javax.swing.text.AbstractDocument;
import javax.swing.text.DocumentFilter;

import util.filters.MaxDigitsDecimalDocumentFilter;
import util.filters.StartsWithZeroMaxDigitsDocumentFilter;

@SuppressWarnings("serial")
public class JDecimalTextField extends JTextField{
	/**
	 * Ukupan broj cifara 
	 */
	private int totalDigits;
	private int decimalPlaces;
	private boolean canHaveLessDigits;
	private char decimalCharacter = ',';
	private String sDecimalCharacter = ",";
	/**
	 * 
	 * @param duzina Ukupna duzina
	 * @param totalDigits Maksimalni broj cifara
	 * @param canHaveLess Da li moze imati i manje cifara
	 * @param canStartWithZero Da li moze poceti sa nulom
	 */
	public JDecimalTextField(int duzina, int totalDigits, int decimalPlaces, char decimalCharacter, boolean canHaveLess){
		super(duzina+1);
		this.totalDigits=totalDigits;
		this.decimalPlaces = decimalPlaces;
		this.decimalCharacter = decimalCharacter;
		this.canHaveLessDigits=canHaveLess;
		AbstractDocument doc = (AbstractDocument)getDocument();
		DocumentFilter filter;
		filter=new MaxDigitsDecimalDocumentFilter(decimalCharacter);;
		((MaxDigitsDecimalDocumentFilter) filter).setMaxLength(totalDigits);
		((MaxDigitsDecimalDocumentFilter) filter).setMaxDecimalPlaces(decimalPlaces);
		doc.setDocumentFilter(filter);
	}
	
	public int numberOfDigits(){
		String contents = getText();
		int retval = 0;
		for(int i = 0; i < contents.length() ; i++){
			if(Character.isDigit(contents.charAt(i))){
				retval++;
			}
		}
		return retval;
	}
	
	public int numberOfDecimals(){
		
		String contents = getText();
		
		if(contents.contains(sDecimalCharacter)){
			if(contents.indexOf(decimalCharacter) == contents.length() - 1){
				return 0;
			}
			String substring = contents.substring(contents.indexOf(decimalCharacter) + 1);
			int retval = 0;
			for(int i = 0; i < substring.length() ; i++){
				if(Character.isDigit(substring.charAt(i))){
					retval++;
				}
			}
			return retval;
		}else{
			return 0;
		}
	}
	
	public double getValue(){
		try{
			String text = getText().replace(decimalCharacter, '.');
			return Double.parseDouble(text);
		}catch(Exception e){
			return 0.0;
		}
	}
	
	public void setValue(double value){
		String s = Double.toString(value);
		if(s.contains(".")){
			s = s.replace(".", ",");
		}
		setText(s);
	}
	/**
	 * Odredjuje da li je validan sadrzaj polja 
	 * @return
	 */
	public boolean isEditValid(){
		if (canHaveLessDigits){
			return numberOfDigits()>0 && numberOfDecimals()<=decimalPlaces;
		}else{
			return numberOfDigits()==totalDigits && numberOfDecimals()<=decimalPlaces;
		}
	}
}
